layui.use(['form','layer','util'],function() {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        util = layui.util;

    // 6、轮询秒杀结果
    function getMiaoshaResult(goodsId){
        g_showLoading();
        $.ajax({
            url:"/miaosha/result",
            type:"GET",
            data:{
                goodsId:goodsId
            },
            success:function(data){
                if(data.code == 0){
                    var result = data.data;
                    if(result < 0){
                        layer.msg("对不起，秒杀失败");
                    }else if(result == 0){// 继续轮询
                        setTimeout(function(){
                            getMiaoshaResult(goodsId);
                        }, 500);
                    }else{
                        layer.confirm("恭喜你，秒杀成功！查看订单？", {btn:["确定","取消"]},
                            function(){
                                window.location.href="/page/order_detail.htm?orderId="+result;
                            },
                            function(){
                                getDetail(goodsId);
                                layer.closeAll();
                            });
                    }
                }else{
                    layer.msg(data.msg);
                }
            },
            error:function(){
                layer.msg("客户端请求有误");
            }
        });
    }
    // 5、执行秒杀
    function doMiaosha(path) {
        $.ajax({
            url:"/miaosha/"+path+"/do_miaosha",
            type:"POST",
            data:{
                goodsId:$("#goodsId").val(),
                verifyCode:$("#verifyCode").val()
            },
            success:function(data){
                if(data.code == 0){
                    getMiaoshaResult($("#goodsId").val());
                }else{
                    layer.msg(data.msg);
                }
            },
            error:function(){
                layer.msg("客户端请求有误");
            }
        });
    }
    // 4、获取秒杀路径
    function getMiaoshaPath(){
        var goodsId = $("#goodsId").val();
        g_showLoading();
        $.ajax({
            url:"/miaosha/path",
            type:"GET",
            data:{
                goodsId:goodsId,
                verifyCode:$("#verifyCode").val()
            },
            success:function(data){
                if(data.code == 0){
                    var path = data.data;
                    doMiaosha(path);
                }else{
                    layer.msg(data.msg);
                }
            },
            error:function(){
                layer.msg("客户端请求有误");
            }
        });
    }
    // 3、刷新验证码
    function refreshVerifyCode(){
        $("#verifyCodeImg").attr("src", "/miaosha/verifyCode?goodsId="+$("#goodsId").val()+"&timestamp="+new Date().getTime());
    }
    // 2、获得数据后，渲染表单
    function renderGoodsDetail(data){
        $("#goodsName").text(data.goods.goodsName);
        $("#goodsImg").attr("src", data.goods.goodsImg);
        $("#goodsDetail").text(data.goods.goodsDetail);
        $("#miaoshaPrice").text(data.goods.miaoshaPrice);
        $("#stockCount").text(data.goods.stockCount);
        $("#startDate").val(util.toDateString(data.goods.startDate));
        $("#endDate").val(util.toDateString(data.goods.endDate));
        $("#userId").val(data.user.id);

        if(new Date(data.goods.startDate).getTime() > new Date(data.currentTimeMillis).getTime()){
            $('#leftTime').val("活动未开始");
            $("#buyBtn").unbind().click(function () {
                layer.msg("活动未开始");
                return false;
            });
        }else if(new Date(data.goods.endDate).getTime() < new Date(data.currentTimeMillis).getTime()){
            $('#leftTime').val("活动已结束");
            $("#buyBtn").unbind().click(function () {
                layer.msg("活动已结束");
                return false;
            });
        }else{
            $("#buyBtn").unbind().attr("lay-filter", "*").attr("lay-submit", "");
            // 倒计时
            util.countdown(data.goods.endDate, data.currentTimeMillis, function(date, serverTime, timer){
                var str = date[0] + '天' + date[1] + '时' +  date[2] + '分' + date[3] + '秒';
                $('#leftTime').val(str);
            });
        }
    }
    // 1、获取商品详情数据
    function getDetail(goodsId) {
        setTimeout(function () {
            $.ajax({
                type: "GET",
                url: "/goods/detail",
                data: {
                    goodsId : goodsId
                },
                dataType: "json",
                success: function(data){
                    if(data.code == 0){
                        renderGoodsDetail(data.data);
                    }else{
                        layer.msg(data.msg);
                    }
                }
            });
        }, 10);
    }

    // 页面初始化
    $(function () {
        // 获取参数
        var goodsId = g_getQueryString("goodsId");
        $("#goodsId").val(goodsId);
        // 获取商品详情
        getDetail(goodsId);
        // 设置图片宽高
        $("#goodsImg").height(500);
        $("#goodsImg").width(400);
        // 初始化验证码图片
        refreshVerifyCode();
    });

    // 给图片绑定点击刷新的事件
    $("#verifyCodeImg").click(function () {
        refreshVerifyCode();
    });

    // 立即秒杀
    form.on('submit(*)', function(data){
        // 获取随机秒杀路径，然后提交数据
        getMiaoshaPath();

        // 刷新验证码
        setTimeout(function () {
            refreshVerifyCode();
        }, 100);

        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

});